package org.csu.webjpetstoreback.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import jakarta.servlet.http.HttpSession;
import org.apache.catalina.session.StandardSessionFacade;
import org.csu.webjpetstoreback.config.CommonResponse;
import org.csu.webjpetstoreback.mapper.InventoryMapper;
import org.csu.webjpetstoreback.model.Inventory;
import org.csu.webjpetstoreback.model.Item;
import org.csu.webjpetstoreback.model.Orders;
import org.csu.webjpetstoreback.model.Product;
import org.csu.webjpetstoreback.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@SessionAttributes(names = "httpSession")
@Validated
public class ItemController {
    @Autowired
    ItemService itemService;
    @Autowired
    InventoryMapper inventoryMapper;

    @GetMapping("/Item/Product/{ProductId}")
    public CommonResponse<List<Item>> GetItemListByProductId(@PathVariable("ProductId")String productId){
        return itemService.GetItemListByProductId(productId);
    }

    //这个指令在于向Item.jsp中存储要取到的Item的值
    @GetMapping("/Item/Item/{ItemId}")
    public CommonResponse<Item> reserveItemId(@PathVariable("ItemId") String itemId, HttpSession session)
    {
        session.setAttribute("itemId",itemId);
        System.out.println();
        System.out.println("reserve Item is "+itemId);
        return CommonResponse.BackForSuccess("保存成功");
    }

    //这个指令在于向Item.jsp中发送要取到的Item的值
    @GetMapping("/Item/newItemForm")
    public CommonResponse<Item> pullItem(HttpSession session)
    {
        String itemId = (String) session.getAttribute("itemId");
        System.out.println();
        System.out.println("get Item is"+itemId);
        return itemService.GetItemByItemId(itemId);
    }


    @GetMapping("/Item/{ItemId}")
    public CommonResponse<Item> GetItemByItemId(@PathVariable("ItemId")String itemId)
    {
        return itemService.GetItemByItemId(itemId);
    }
    @GetMapping("/Inventory/{ItemId}")
    public CommonResponse<Inventory> getInventoryByItemId(@PathVariable("ItemId")String itemId){
        return  itemService.getInventoryByItemId(itemId);
    }
    @PutMapping("PutInventory")
    public CommonResponse<Inventory> PutInventory(Inventory inventory){
        UpdateWrapper<Inventory> UpdateWrapper = new UpdateWrapper<>();
        int result = inventoryMapper.update(inventory,UpdateWrapper);
        if (result ==1){
            return CommonResponse.BackForSuccess("inventory修改成功");
        }else{
            return CommonResponse.BackForError("inventory修改失败");
        }
    }
}
